<?php
/**
 * $Id: cms_users_controller.php 708 2014-06-28 11:23:53Z vishal $
 * 
 * This file can not be redistributed to anyone without the permission of Giga Promoters
 * Copyright 2005 - 2008, Giga Promoters
 * 						  608 Aggarwal Cyber Plaza
 *						  Netaji Subhash Place, Delhi - 110034
 *						  www.gigapromoters.com
 * 
 *
 * @version 			$Rev: 708 $
 * @lastModifiedBy		$LastChangedBy: vishal $
 * @lastChanged			$Date: 2014-06-28 16:53:53 +0530 (Sat, 28 Jun 2014) $
 * @copyright 			Giga Promoters (www.gigapromoters.com)
 * 
 */

class CmsUsersController extends UsersAppController
{
	var $name = 'Users';
	var $components = array('Session', 'Email', 'Auth', 'RequestHandler', 'Cookie');
	var $helpers = array('Html','Form', 'Javascript', 'Time', 'Cms.Index','Cms.Restricted','Effects.Navigation');
	var $userModelAlias = 'User';
	var $view = 'Users.User';
	var $lastLoginResult = null;
	
	/**
	 * Tells View class to look into additional path for child classes
	 * (non-PHPdoc)
	 * @see app/plugins/cms/GigaAppController#beforeRender()
	 */
	function beforeRender()
	{
		if($this->name != 'Users')
		{
			$viewPaths = am(Configure::read('viewPaths'), USERS_PATH.'views'.DS);
			Configure::write('viewPaths', $viewPaths);
		}
		parent::beforeRender();
	}
	
	function _getUserModel()
	{
		return $this->{$this->userModelAlias};
	}

	/**
	 * Set params for authorization class
	 *
	 */
	function beforeFilter() {
		$this->Auth->allow('login', 'logout', 'activate', 'index', 'register', 'forgotPassword', 'updatePassword', 'profile','resendSignupNotification');
		$this->Auth->userModel = $this->userModelAlias;
		$this->Auth->loginAction = array('action'=>'login');
		$this->Auth->loginRedirect = array('action'=>'myAccount');
		$this->Auth->logoutRedirect = '/';
		$this->Auth->fields = array('username' => 'email', 'password' => 'password');
		$this->Auth->authorize = array('model'=>$this->userModelAlias);
		$this->Auth->autoRedirect = false;
		$userModelAlias = $this->userModelAlias;
		//prd($this);
		$this->set(compact('userModelAlias'));
		parent::beforeFilter();
	}
	
	/**
	 * Function for hooks to override login permisions etc
	 */
	function _overrideLogin($msg = false, $result = true, $redirectTo = false)
	{
		$this->lastLoginResult = compact('msg', 'result', 'redirectTo');
	}
	
	/**
	 * Performs login action based on given paramaters
	 * check whether we have to redirect or we return the login response in case of 'requestAction'
	 */
	private function _login($msg = false, $result = true, $redirectTo = false)
	{
		$this->set('loginResponse', compact('msg', 'result', 'redirectTo'));

		unset($this->data[$this->userModelAlias]['password']);
		
		if($result)
		{
			$this->Session->write('Auth.model',$this->userModelAlias);
			callHooks('afterLogin', null, $this);
			$this->_afterLogin();
			$msgFunc = 'successMsg';
		}
		else
		{
			$msgFunc = 'errorMsg';
			$this->Auth->logout();
		}
		if(isset($this->params['requested']) && $this->params['requested'])
		{
			return $result;
		}	
		if($msg)
		{
			$this->{$msgFunc}(__($msg));	
		}
		
		if($redirectTo)
			$this->redirect($redirectTo);
	}

	function login()
	{
		// hooked events
		$this->_beforeLogin();
		callHooks('beforeLogin', null, $this);
		//set referer as redirect if no redirect is present in session or redirectBack is true.
		if(strpos($this->referer(),'login')===false && (($this->data && !$this->Session->check('Auth.redirect')) || (isset($this->params['named']['redirectBack']) && $this->params['named']['redirectBack']=='true')))
		{
			$this->Session->write('Auth.redirect',$this->referer());
		}
		if(!$this->data)
		{
			if($userInfo=$this->Cookie->read('userInfo'))
			{
				if($this->Auth->login($userInfo))
				{
					return $this->_login(false, true, $this->referer());
				}
			}
		}
		$this->pageTitle= __('Login');
		
		if(empty($this->data) == false)
		{
			// before performing login, make sure there are no restrictions from hooks
			if(is_array($this->lastLoginResult))
			{
				return $this->_login($this->lastLoginResult['msg'], $this->lastLoginResult['result'], $this->lastLoginResult['redirectTo']);
			}
			
			if($this->Auth->login($this->data[$this->userModelAlias]))
			{
				// get logged in user
				$user = $this->Auth->user();
				
				// check if user is blocked - in case user deactive is enabled
				if($user[$this->userModelAlias]['is_deactivated']==1)
				{
					return $this->_login('Can not login, Your account has been blocked by admin.', false);
				}

				// check if user is activated - in case user email verification is enabled
				if($this->_getUserModel()->emailVerification && $user[$this->userModelAlias]['emailVerified']==0)
				{
					return $this->_login('Login failed. Please activate your account first.', false);
				}

				// check if user is approved by admin, when enabled
				if($this->_getUserModel()->adminVerification && $user[$this->userModelAlias]['adminVerified']==0)
				{
					return $this->_login('Login failed. Administrator has not reviewed your account yet.', false);
				}
				
				// when login is successful, create a login cookie so user does not have to login again
				if(isset($this->data[$this->userModelAlias]['remember_me']) && $this->data[$this->userModelAlias]['remember_me'])
				{
					$cookie['email'] = $this->data[$this->userModelAlias]['email'];
					$cookie['password'] = $this->data[$this->userModelAlias]['password'];
					$this->Cookie->write('userInfo', $cookie  , true, '+2 weeks');
					unset($this->data[$this->userModelAlias]['remember_me']);
				}
				
				//update on user login
				if($authedUser = $this->Session->read('Auth.'.$this->userModelAlias))
				{
					// save tracking stuff
					$update_user['id'] = $authedUser['id'];
					$update_user['last_login_date'] = date('Y-m-d H:i:s');
					$update_user['lastLoginIpAddr'] = $this->RequestHandler->getClientIP();
					$this->_getUserModel()->save(array($this->_getUserModel()->alias => $update_user),array('validate'=>false,'callbacks'=>false ));
					
					$this->user = $update_user;
					
					// hooked events
					
					// redirect user to its account or someother page
					if($this->Session->read('Login.redirect'))
					{
						$redirectUrl = $this->Session->read('Login.redirect');
						$this->Session->del('Login.redirect');
					} 
					else 
					{
						$redirectUrl = $this->Auth->redirect();
					}
					return $this->_login('Logged in successfully', true, $redirectUrl);
				}
			}
			else
			{
				return $this->_login('Log in failed', false);
			}

		}

		// check if user already logged in
		if($this->Session->read('Auth.'.$this->userModelAlias))
		{
			return $this->_login(false, true, $this->Auth->redirect());
		}
	}

	/**
	 * Simple logout - Needs permission before editing
	 * Needs permission before editing.
	 *
	 */
	function logout()
	{
		callHooks('onLogout', null, $this);
		$this->Session->del('Auth.model');
		$this->_afterLogout();
		$this->Cookie->del('userInfo');
		$this->successMsg(__("You've successfully logged out."));
		$this->redirect($this->Auth->logout());
	}

	/**
	 * Handles registration of different user types.
	 * Check for flaws etc. Needs permission before editing.
	 *
	 * @param unknown_type $userType
	 */
	function register($userType='default')
	{
		/*if($this->Session->read('Auth.User'))
		{
			$this->redirect($this->referer());
		}*/
		callHooks('beforeRegister', null, $this);
		$this->_beforeRegister();
		
		$this->pageTitle = __('User Registration');
		$this->set('userType', $userType);
		
		if(!empty($this->data))
		{
			// @todo improve validation code generation and make it unique
			$this->data[$this->userModelAlias]['validateCode'] = $this->_getUserModel()->generateRandomUniqueValue('validateCode');
			$this->data[$this->userModelAlias]['date_joined'] = date('Y-m-d h:i:s');
			//$this->data[$this->userModelAlias]['userType'] = $userType;
			$this->data[$this->userModelAlias]['lastLoginIpAddr'] = $this->RequestHandler->getClientIP();
			
			$captchaKey = null;
			if(isset($this->data[$this->userModelAlias]['captcha']))
			{
				$captchaKey = $this->data[$this->userModelAlias]['captcha'];
			}

			//$validCaptcha = false;
			$validCaptcha = false;
			if($this->_getUserModel()->useCaptcha == false)
			{
				$validCaptcha = true;
			}else
			{
				$validCaptcha = $this->verifyCaptcha($captchaKey);
			}
            //Set emailVerified in case Email Verification is not required.
            if($this->_getUserModel()->emailVerification == false)
            {
              $this->data[$this->userModelAlias]['emailVerified'] = 1;
            }
			$this->_getUserModel()->create();
			if($validCaptcha && $this->_getUserModel()->save($this->data))
			{
				$new_user_id = $this->_getUserModel()->getLastInsertId();
				$condition = array();
				$condition[$this->userModelAlias.'.id'] = $new_user_id;
				$someone = $this->_getUserModel()->find('first', array('conditions' => $condition));

				$this->Session->write($this->userModelAlias, $someone[$this->userModelAlias]);

				if($this->_getUserModel()->emailVerification)
				{
					$this->sendActivationEmail($someone);		
					$this->successMsg(__('Please check your inbox and click the activation link from mail we just sent you.'));
					
				}
				else
				{
					$authlogin[$this->userModelAlias] = array('email'=>$this->data[$this->userModelAlias]['email'], 'password'=>$this->data[$this->userModelAlias]['password']);
					$this->Auth->login($authlogin[$this->userModelAlias]);
					$this->successMsg(__('Successfully logged in.'));

				}
				
				// user plugin callback - first - to be implemented
				callHooks('afterRegister', null, $this, $someone[$this->userModelAlias]);
				$this->_afterRegister($someone);
				if($this->_getUserModel()->emailVerification == false)
					$this->redirect($this->Auth->loginRedirect);
				$this->render('register_success');
			}
			else  // if not saved
			{
				if($validCaptcha == false)
				{
					$this->errorMsg(__('CAPTCHA code not valid.'));
				}
				else
				{
					$this->errorMsg(__('Unable to register. Please check form errors below.'));
					$this->log('Registration failed. Validation errors:'. print_r($this->_getUserModel()->validationErrors, true), LOG_INFO);
				}

				unset($this->data[$this->userModelAlias]['password']);
				unset($this->data[$this->userModelAlias]['confirm_password']);
			}
		}
		else
		{
			// check user type
			if(!in_array($userType, Configure::read('userTypes')))
			{
				$this->warningMsg(__("Can not register this user type."));
				$this->redirect($this->referer());
			}
		}
	}

	/**
	 * This function verifies user email.
	 * Needs permission before editing.
	 *
	 * @param unknown_type $code
	 */
	function activate($code)
	{
		$this->_getUserModel()->recursive = -1;
		$user = $this->_getUserModel()->find(array($this->userModelAlias.'.validateCode'=>$code));
		$this->user = $user;
		
		if(!empty($user))
		{
			if($user[$this->userModelAlias]['emailVerified']==1)
			{
				$this->infoMsg(__('Your account is already activated.'));
				$this->redirect($this->Auth->loginAction);				
			}
			$this->_getUserModel()->id = $user[$this->userModelAlias]['id'];
			if($this->_getUserModel()->saveField('emailVerified', 1))
			{
				$this->successMsg(__('Account activated successfully.'));
				$this->_afterUserActivate($user[$this->userModelAlias]); // callback for inherited controllers
				
				callHooks('afterUserActivate', null, $this ,$user[$this->userModelAlias]['id']); // plugin callbacks

				$this->redirect($this->Auth->loginAction);
			}
			else
			{
				$this->errorMsg(__('Unable to activate account. Please contact administrator.'));
			}
		}
		else
		{
			$this->errorMsg(__('Unable to retrieve user. Please contact administrator if you think this is an error.'));
		}
		$this->redirect('/');
	}

	/**
	 * Callback function to be used in inherited controllers
	 * @return unknown_type
	 */
	function _afterUserActivate() {}

	/**
	 * Before register callback
	 * @return unknown_type
	 */
	function _beforeRegister() { }
		
	/**
	 * Before login callback
	 * @return unknown_type
	 */
	function _beforeLogin() { }
	
	/**
	 * Callback function triggered after login
	 * @return unknown_type
	 */
	function _afterLogin() {}	
	
	/**
	 * Callback function triggered after login
	 * @return unknown_type
	 */
	function _afterLogout() {}
	
	/**
	 * Called when admin verifies the user from backend
	 */
	function _afterAdminVerification() {}
	
	/**
	 * My account page.
	 * Needs permission before editing.
	 *
	 */
	function myAccount()
	{
		callHooks('myAccount', '.+', $this);

		$this->pageTitle='My Account';
		$authedUser = $this->Session->read('Auth.'.$this->userModelAlias);

		$this->_getUserModel()->recursive = -1;
		$user = $this->_getUserModel()->FindById($authedUser['id']);

		$this->set('user', $user);
	}

	/**
	 * User's profile page
	 * Needs permission before editing.
	 *
	 * @param can be user_id or username $user
	 */
	function profile($user=null)
	{
		$this->pageTitle= __('Profile');
		if(is_numeric($user))
		{
			$conditions = array($this->userModelAlias.'.id' => $user);
		}
		elseif(is_string($user))
		{
			$conditions = array($this->userModelAlias.'.username' => $user);
		}
		if(is_null($user))
		{
			$userId = $this->Session->read('Auth.'.$this->userModelAlias.'.id');
			$conditions = array($this->userModelAlias.'.id' => $userId);
		}
		$user = $this->_getUserModel()->find('first', compact('conditions'));
		if(empty($user))
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect($this->referer());
		}
		if(isset($user[$this->userModelAlias]['private_profile']) && $user[$this->userModelAlias]['private_profile']==1)
		{
			// check if viewer is logged in
			if(!$this->Session->check('Auth.'.$this->userModelAlias.'.id'))
			{
				$this->warningMsg(__('You need to login to view profile of this member.'));
				$this->redirect($this->referer());
			}
		}
		$this->set(compact('user','profileFields'));
		
		// add count to profile views
		if($this->_getUserModel()->hasField('profile_views'))
		{
			$this->_getUserModel()->updateAll(array($this->userModelAlias.'.profile_views'=>$this->userModelAlias.'.profile_views+1'), array($this->userModelAlias.'.id'=>$user[$this->userModelAlias]['id'])); 
		}
		
	}

	/**
	 * Users listing function. Its commented because its not needed here. Probably we can handle this by a config variable.
	 * Needs permission before editing.
	 
	function index()
	{
	$this->pageTitle='Members List';
	$this->User->recursive = 0;
	$this->set('users', $this->paginate(array("User.status"=>"1")));

	*/

	/**
	 * Handles forgot password procedure.
	 * Needs permission before editing.
	 *
	 */
	function forgotPassword()
	{
		$this->pageTitle = __('Forgot Password? Get it now!');
		if($this->data)
		{
			$this->_getUserModel()->recursive = -1;
			$email_user = $this->_getUserModel()->findByEmail($this->data[$this->userModelAlias]['email']);
			if($email_user)
			{
				//$this->Email->delivery = 'debug';
				$this->Email->to = $this->data[$this->userModelAlias]['email'];
				$this->Email->subject = 'Forgot Password';
				$this->prepareEmail();
				$this->Email->template = 'forgot_password';
				$changepass_url = Router::url(array("action"=>"updatePassword",$email_user[$this->userModelAlias]["validateCode"]),true);
				$changepass_link = "<a href='".$changepass_url."'>Click to reset your password.</a>";
				$this->set('name', isset($email_user[$this->userModelAlias]['name']) ?  $email_user[$this->userModelAlias]['name'] : $email_user[$this->userModelAlias]['full_name']);
				$this->set('changepass_link', $changepass_link);
				$this->set('changepass_url', $changepass_url);
				$this->set('changePasswordCode', $email_user[$this->userModelAlias]["validateCode"]);
				$this->set('siteurl', Configure::read('cmsConfig.Backend.siteUrl'));
				$this->set('sitename', Configure::read('cmsConfig.Backend.siteName'));

				//to debug
				$this->Email->send();
				$this->successMsg(__("All necessary information to reset the password has been sent to your account."));
				$this->redirect('/');

			}
			else
			{
				$this->errorMsg(__("Sorry, this email does not exist in our database."));
			}
		}
	}

	/**
	 * After user clicks on forgot password email. This function handles password reset
	 * Needs permission before editing.
	 *
	 * @param unknown_type $code
	 */
	function updatePassword($code = false)
	{
		$this->pageTitle = __('Reset your password now');
		$passwordLength = $this->_getUserModel()->passwordLength;
		if($this->Session->check('Auth.'.$this->userModelAlias.'.id')==true)
		{
			$this->redirect('/');
		}
		$this->_getUserModel()->recursive = -1;
		$email_user = $this->_getUserModel()->findByValidatecode($code);
		if(empty($email_user))
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect('/');
		}
		if($this->data)
		{
			if($this->data[$this->userModelAlias]['password']==$this->data[$this->userModelAlias]['confirm_password'])
			{
				if(strlen($this->data[$this->userModelAlias]['confirm_password']) < $passwordLength)
				{
					$this->errorMsg(sprintf(__("Minimum password length %s characters."),$passwordLength));
					$this->redirect(array('action'=>'updatePassword/'.$code));
				}
				$email_user[$this->userModelAlias]['password'] = $this->Auth->password($this->data[$this->userModelAlias]['password']);
				$this->_getUserModel()->id = $email_user[$this->userModelAlias]['id'];
				$this->_getUserModel()->saveField('password',$email_user[$this->userModelAlias]['password']);
				callHooks('AfterPasswordUpdate','.+',$this);
				$this->successMsg(__("Password updated successfully, Please login."));
				$this->redirect($this->Auth->loginAction);
			}
			else
			{
				$this->errorMsg(__("The passwords do not match, Please enter again."));
				$this->redirect(array('action'=>'updatePassword/'.$code));
			}
		}
		$this->set('validate_code', $code);
	}

	/**
	 * Modifies password. Simple function
	 * Needs permission before editing.
	 *
	 */
	function changePassword_old()
	{
		//prd($this->data);
		$this->pageTitle = 'Change password';
		if($this->data)
		{
			
			if($this->data[$this->userModelAlias]['password']==$this->data[$this->userModelAlias]['confirm_password'] && $this->data[$this->userModelAlias]['password']!='')
			{
				$pass = $this->data[$this->userModelAlias]['confirm_password'];
				if(strlen($this->data[$this->userModelAlias]['confirm_password']) < 6)
				{
					$this->errorMsg(__("Password should be atleast 6 characters long."));
					$this->redirect(array('action'=>'changePassword'));
				}
				$authedUser = $this->Session->read('Auth.'.$this->userModelAlias);
				//prd($authedUser);
				$this->_getUserModel()->id = $authedUser['id'];
				$this->_getUserModel()->saveField('password', $this->Auth->password($this->data[$this->userModelAlias]['password']));
				
				callHooks('AfterPasswordUpdate','.+',$this);
				
				$this->successMsg(__("Your password has been reset."));
				$this->redirect(array('action'=>'myAccount'));
			}
			else
			{
				$this->errorMsg(__("The passwords does not match, Please enter again."));
				$this->redirect(array('action'=>'changePassword'));
			}
		}
	}
	
	/**
	 * Admin management for users.
	 * Needs permission for editing.
	 *
	 */
	function admin_index($type = null)
	{
		$this->pageTitle = __($this->userModelAlias.' List');
		$this->_getUserModel()->recursive=0;
		
		$gridFields = $this->_getUserModel()->getFields('group', 'grid');
		$this->set(compact('gridFields'));
		
		if(!is_null($type))
		{
			$this->paginate['conditions']['userType'] = $type;
			$this->set('type', $type);
		}
		if(!isset($this->paginate['limit']))
		{
			$this->paginate['limit'] = 15;
		}
		$this->paginate['order'] = $this->userModelAlias.'.created DESC';
		$this->set('users', $this->paginate());
	}
	
	/**
	 * View user - for backend.
	 * Needs permission for editing.
	 *
	 * @param unknown_type $id
	 */
	function admin_view($id = null) {
		if (!$id) {
			$this->errorMsg(__('Invalid User.', true));
		}
		$users=$this->_getUserModel()->findById($id);
		$this->set('user',$users);
		//pr($users);
	}
	
	// * @param unknown_type $id
	

	function admin_edit($id = null) 
	{
		$this->pageTitle = __("Users");
		$userData = $this->User->findById($id);
		if (empty($userData))
		{
			$this->errorMsg(__('Invalid user for editing!'));
			$this->redirect('/admin/users');		
		}
		if (!empty($this->data)) 
		{
			$this->data['User']['id'] = $userData['User']['id'];
			
			if ($this->User->save($this->data)) 
			{
				$this->successMsg(__('User modified!'));
				$this->redirect(array('action'=>'admin_index'));
			} 
			else
			{
				$this->errorMsg(__('Sorry, data has not been edited! Please try again.'));
			}
		}
		if (empty($this->data)) 
		{
			$this->data = $userData;
		}
		$this->set('countries',array_combine(Utility::getCountries(),Utility::getCountries()));
		$this->set(compact('userData'));
	}
	/*function admin_edit_old($id = null) 
	{
		if (!$id && empty($this->data)) {
			$this->flash(__('Invalid User', true), array('action'=>'index'));
		}
		if (!empty($this->data)) 
		{
			if ($this->User->save($this->data)) 
			{
				$this->successMsg('User modified!');
				$this->redirect(array('action'=>'admin_index'));
			} 
			else
			{
				$this->errorMsg('Sorry, data could not be updated! Please try again.');
			}
		}
		if (empty($this->data)) 
		{
			$this->data = $this->User->findById($id);
		}
	}*/
	

	/**
	 * Delete users for backend.
	 * Needs permission for editing.
	 *
	 * @param unknown_type $id
	 */
	function admin_delete($id = null) {
		if (!$id) 
		{
			$this->errorMsg(__('Invalid id for User', true));
			$this->redirect($this->referer());
		}
		$user = $this->_getUserModel()->findById($id);
		$this->_getUserModel()->id = $id;
		$currentModel = $this->_getUserModel()->alias;
		$singularizedCurrentModel = Inflector::singularize($currentModel);
		if ($this->_getUserModel()->delete($id, true)) 
		{
			callHooks('AfterUserDelete', null, $this, $id);
			$this->successMsg(__('User deleted', true));
			$this->redirect($this->referer());
		}
	}
	
	/**
	 * Admin verification functionality.
	 *
	 * @param unknown_type $id
	 */
	function admin_verify($id = null) {
		if (!$id) {
			$this->errorMsg(__('Invalid id for User', true));
			$this->redirect($this->referer());
		}
		$user = $this->_getUserModel()->findById($id);
		$this->_getUserModel()->id = $id;			
		if ($this->_getUserModel()->saveField('adminVerified','1')) 
		{
			$this->_afterAdminVerification();
			callHooks('AfterAdminVerification', '.+', $this);
			$this->successMsg(__('User Verified.', true));
			$this->redirect($this->referer());
		}
		
	}
	
	/**
	 * Block users functionality.
	 * Needs permission for editing.
	 *
	 * @param unknown_type $id
	 */
	function admin_block($id = null) {
		if (!$id) {
			$this->errorMsg(__('Invalid id for User', true));
			$this->redirect('/admin/users/index');
		}
		$user = $this->_getUserModel()->findById($id);
		$this->_getUserModel()->id = $id;			
		if ($this->_getUserModel()->saveField('is_deactivated','1')) 
		{
			callHooks('AfterUserBlocked', '.+', $this);
			$this->successMsg(__('User blocked.', true));
			$this->redirect('/admin/users/index');
		}
		
	}
	
	/**
	 * Unblock functionality.
	 * Needs permission for editing.
	 *
	 * @param unknown_type $id
	 */
	function admin_unblock($id = null) {
		if (!$id) {
			$this->errorMsg(__('Invalid id for User', true));
			$this->redirect('/admin/users/index');
		}
		$user = $this->_getUserModel()->findById($id);
		$this->_getUserModel()->id=$id;			
		if ($this->_getUserModel()->saveField('is_deactivated','0')) 
		{
			callHooks('AfterUserUnblocked', '.+', $this);
			$this->successMsg(__('User unblocked.', true));
			$this->redirect('/admin/users/index');
		}
	}

	/**
	 * Admin search function. Not standardized.
	 *
	 */
	function admin_search()
	{
		if($this->data[$this->userModelAlias]['keyword'])
		$this->Session->write('user_keyword', $this->data[$this->userModelAlias]['keyword']);

		$keyword = urldecode($this->Session->read('user_keyword'));

		$criteria = $this->userModelAlias.".username LIKE ('%".$keyword."%') OR ".$this->userModelAlias.".email LIKE ('%".$keyword."%')";

		$this->_getUserModel()->recursive = 0;
		$this->set('users', $this->paginate(array($criteria)));
		$this->render('admin_index');
	}
	
	/**
	 * Admin change password. Not standardized.
	 *
	 * @param unknown_type $id
	 */
	function admin_change_password_old($id=null)
	{
		if(!empty($this->data))
		{
			$id = $this->data[$this->userModelAlias]['id'];
			$this->_getUserModel()->id = $id;
			$this->data[$this->userModelAlias]['id'] = $id;
			if($this->_getUserModel()->save($this->data))
			{
				$this->successMsg(__('Password has been changed!'));
				$this->redirect(array('plugin'=>'users','controller'=>'users','action'=>'admin_index'));
			}
			else
			{
				$this->errorMsg(__('Password could not be changed.'));
			}
			
		}else
		{
			$this->data[$this->userModelAlias]['id'] = $id;
		}

	}
	
	function editProfile()
	{
		$this->pageTitle = __('Edit Profile');
		$authedUser = $this->Session->read('Auth.'.$this->userModelAlias);

		if (!empty($this->data))
		{
			$this->data[$this->userModelAlias]['id']=$authedUser['id'];
			if ($this->_getUserModel()->save($this->data))
			{
				callHooks('AfterEditProfile','.+',$this);
				$this->successMsg(__("Your profile has been updated."));
				$this->redirect(array('controller'=>'users','action'=>'profile','plugin'=>'users'));
			} 
			else
			{
				$this->errorMsg(__("Unable to update your profile."));
			}
		}
		else
		{
			$this->data = $this->_getUserModel()->findById($authedUser['id']);
			
			// hack for auto populating country when not set
			if($this->_getUserModel()->hasField('country'))
			{
				if(isset($this->data[$this->userModelAlias]['country']) && $this->data[$this->userModelAlias]['country'] == '')
				{
					$loc = Utility::getClientLocation();
					$loc = $loc['CountryCode'];
					$this->data[$this->userModelAlias]['country'] = $loc;
				}
			}
		}
	}	
	/**
	 * changePassword created by varun
	 *
	 * @param unknown_type $id
	 */
	function changePassword($userId = null)
	{
		$this->pageTitle = __('Change Password');
		$passwordLength = $this->_getUserModel()->passwordLength;
		$refererUrl = $this->referer();
		$this->_getUserModel()->recursive = -1;
		if(empty($userId) && !isset($this->params['admin']))
		{
			$authedUser = $this->Session->read('Auth.'.$this->userModelAlias);
			$userId = $authedUser['id'];			
		}
		$userData = $this->_getUserModel()->findById($userId);
		if(empty($userData))
		{			
			$this->errorMsg(__('Invalid URL.'));
			$this->redirect($refererUrl);
		}		
		
		if(!empty($this->data))
		{			
			$this->data[$this->userModelAlias]['id'] = $userData[$this->userModelAlias]['id'];
			$new_password = $this->data[$this->userModelAlias]['password'];
			$confirm_password = $this->data[$this->userModelAlias]['confirm_password'];
			$returnStatus = true;
			if(isset($this->data[$this->userModelAlias]['current_password']))
			{
				$current_password = $this->Auth->password($this->data[$this->userModelAlias]['current_password']);				
				$passwordData = $this->_getUserModel()->findByPasswordAndId($current_password,$userId);	
				if(empty($passwordData))
				{
					$this->_getUserModel()->validationErrors['current_password'] = __('Password does not exist in our database');
					$returnStatus = false;
				}else
				{					
					$returnStatus = true;			
				}
			}
			if(strlen($new_password)<$passwordLength)
			{
				$this->_getUserModel()->validationErrors['password'] = sprintf(__('Password length should be equal or greater than %d',true),$passwordLength);				
				$returnStatus = false;
				
			}elseif($new_password!=$confirm_password)
			{
				$this->_getUserModel()->validationErrors['password'] = __('password  and confirm password does not match');
				$returnStatus = false;
				
			}				
			if($returnStatus==true)
			{
				$this->_getUserModel()->id = $this->data[$this->userModelAlias]['id'];
				$this->_getUserModel()->saveField('password',$this->Auth->password($new_password));
				//hook call when user changes the password.
				callHooks('onPasswordChange',null,$this);
				$this->successMsg(__('Password has been changed!'));
				$this->redirect($refererUrl);
			}
			else
			{
				$this->errorMsg(__('Password could not be changed!'));
			}

		}
		$this->set('userId',$userId);		
	}
	/**
	 * Admin change password. created by varun
	 *
	 * @param unknown_type $id
	 */

	function admin_changePassword($userId= null)
	{
		$this->changePassword($userId);
	}
	/**
	 * Interface method for resendig actiavation email
	 */
	function resendSignupNotification()
	{
		if($this->getAuthModel('id') || $this->_getUserModel()->emailVerification == false)
		{
			$this->redirect($this->referer());
		}
		if($this->data)
		{
			$email = null;
			$validationError = false;
			if(isset($this->data[$this->userModelAlias]['email']))	
			{
				//check whether email exist.
				$email = $this->data[$this->userModelAlias]['email'];
				if($this->_getUserModel()->hasAny(array($this->userModelAlias.'.email'=>$email)) == false)
				{
					$validationError = __("This email does not exist in our database.");
				}else if($this->_getUserModel()->field('emailVerified',array('email'=>$email)) ==1)
				{
					$validationError = __("This account is already active.");
				}
				if($validationError ===false)
				{
					$this->_getUserModel()->recursive = -1;
					$user = $this->_getUserModel()->findByEmail($email);
					$this->sendActivationEmail($user);
					$this->successMsg(__("Please check your inbox and click the activation link from mail we just sent you."));
					$this->redirect(array('action'=>"login"));
				}else
				{
					$this->errorMsg($validationError);
					//$this->_getUserModel()->validationErrors['email'] = $validationError;
					$this->set('validationError',$validationError);
				}
			}
		}
		
	}
	
	protected function sendActivationEmail($user)
	{
		$this->prepareEmail();
		$this->Email->to = $user[$this->userModelAlias]['email'];
		$this->Email->subject = 'Account activation';
		$this->Email->sendAs = 'both';
		$this->Email->template = 'register';
		// set activation links		
		$activation_url = Router::url(array('action' => 'activate', $user[$this->userModelAlias]["validateCode"],'admin'=>false),true);
		$activation_link = "<a href='".$activation_url."'>".__("Click to activate")."</a>";
		//if(isset($someone[$this->userModelAlias]['username']))
		$this->set('name', $user[$this->userModelAlias]['full_name']);
		$this->set('activationCode', $user[$this->userModelAlias]["validateCode"]);
		$this->set('activation_url', $activation_url);
		$this->set('activation_link', $activation_link);
		$this->set('siteurl', Configure::read('cmsConfig.Backend.siteUrl'));
		$this->set('sitename', Configure::read('cmsConfig.Backend.siteName'));
		//to send mail
		return $this->Email->send();
	}
	
	function admin_resendSignupNotification($id)
	{
		$this->_getUserModel()->recursive = -1;
		$user = $this->_getUserModel()->findById($id);
		if($user)
		{
			$this->sendActivationEmail($user);
			$this->successMsg(__("Activation email has been sent to user."));
		}
		$this->redirect($this->referer());
	}
	
	function _afterRegister()
	{
		
	}
	
	function admin_addBadWords()
	{		
		$this->pageTitle = __('Specify Bad Words');
		$pathToBadWordFile = APP."plugins".DS."users".DS."bad_words_file.txt";
		if($this->data)
		{
			$badWordData = $this->data['User']['badWords'];
			if(file_put_contents($pathToBadWordFile,$badWordData) || empty($badWordData))
			{
				$this->successMsg(__('Bad word file has been modified.'));
			
			}else
			{
				$this->errorMsg('Bad word file could not be modified!');
			}
		}
		if(file_exists($pathToBadWordFile))
		{
			$this->data['User']['badWords'] = file_get_contents($pathToBadWordFile);
		}		
	}

}
?>
